package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2024/10/14 9:52
 * @Version 1.0
 */
@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Value("${sky.wechat.appid}")
    private String appId;
    @Value("${sky.wechat.secret}")
    private String secret;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;


    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //用户微信登录，完成自动注册
        //1.要去微信端获取openid
        String openId = getOpenId(dto.getCode());
        if(!StringUtils.hasText(openId)){
            throw new BaseException("未获取到openId");
        }
        //2.根据Openid去数据库里面找下，检查是否已经存在
        User user = userMapper.getByOpenId(openId);
        //3.如果不存在，添加数据
        if(user == null){
            user = new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openId);
            userMapper.insert(user);
        }
        //4.生成token
        Map<String,Object> param = new HashMap<>();
        param.put("openId",openId);
        param.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), param);

        //获取商家信息
        Merchant merchant = merchantMapper.getById(1L);
        //计算费用
        String lnglat = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal cost = MapUtils.getDelivoryCost(lnglat, dto.getLocation());

        //5.构造返回结果
        UserLoginVO loginVO = UserLoginVO.builder().token(token)
                .shopTelephone(merchant.getShopTelephone())
                .shopName(merchant.getShopName())
                .shopAddress(merchant.getShopAddress())
                .deliveryFee(cost)
                .shopId(merchant.getId())
                .openid(openId)
                .build();
        return loginVO;
    }

    /**
     * 获取Openid
     * @param code
     * @return
     */
    private String getOpenId(String code){

        Map<String,String> param = new HashMap<>();
        param.put("appid",appId);
        param.put("secret",secret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        String response = HttpClientUtil.doGet(URL, param);
        log.info("微信登录返回：{}",response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = (String)jsonObject.get("openid");
        return openid;
    }
}